<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.keyword" placeholder="关键字"></el-input>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @current-change="handleCurrentChange"  :page-size="pageSize" :total="total" v-on:click="getEmployees">查询</el-button>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<!--name
		tel
		registerTime
		state
		address
		logo
		admin_id-->
		<el-table :data="shops" highlight-current-row v-loading="listLoading" @selection-change="selsChange" style="width: 100%;">
			<el-table-column type="selection">
			</el-table-column>
			<el-table-column type="index">
			</el-table-column>
			<el-table-column prop="name" label="店铺名称" sortable>
			</el-table-column>
			<el-table-column prop="" label="店长"  sortable>
			</el-table-column>
			<el-table-column prop="registerTime" label="注册时间"  sortable>
			</el-table-column>
			<el-table-column prop="phone" label="电话" sortable>
			</el-table-column>
			<el-table-column prop="address" label="地址" sortable>
			</el-table-column>
			<el-table-column prop="state" label="状态"   sortable>
				<!--这里我们给状态定义一个颜色为了视觉效果更好，经测试只能写在这里，和下面的操作一样
                scope.row是拿到当前行的值-->
				<template scope="scope">
					<span style="color: darkgray" v-if="scope.row.state==0">待提交</span>
					<span style="color: orange" v-else-if="scope.row.state==1">待审核</span>
					<span style="color: red" v-else-if="scope.row.state==-1">被驳回</span>
					<span style="color: red" v-else-if="scope.row.state==2">审核通过</span>
					<span style="color: #475669" v-else>未知</span>
				</template>
			</el-table-column>
			<el-table-column prop="logo" label="标志"  sortable>
			</el-table-column>
			<el-table-column label="操作">
				<template scope="scope">
					<el-button size="warning" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					<el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)" float="left">删除</el-button>
					<el-button type="primary" size="small" @click="handleSub(scope.$index, scope.row)" float="right">提交</el-button>
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
			<el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"  :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>

		<!--编辑界面-->
		<el-dialog destroy-on-close :title="title" :visible.sync="employeeFormVisible" :close-on-click-modal="false">
			<el-form :model="employeeForm" label-width="80px" :rules="employeeFormRules" ref="employeeForm">
				<el-form-item label="姓名" prop="username">
					<el-input v-model="employeeForm.username" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
					<el-input v-model="employeeForm.email" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="电话" prop="phone">
					<el-input v-model="employeeForm.phone" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="年龄">
					<el-input-number v-model="employeeForm.age" :min="0" :max="200"></el-input-number>
				</el-form-item>
				<el-form-item label="状态">
					<el-radio-group v-model="employeeForm.state">
						<el-radio class="radio" :label="1">正常</el-radio>
						<el-radio class="radio" :label="0">禁用</el-radio>
					</el-radio-group>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button @click.native="employeeFormVisible = false">取消</el-button>
				<el-button type="primary" @click.native="save" :loading="employeeLoading">提交</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
    import util from '../../common/js/util'
    //import NProgress from 'nprogress'
    import { getUserListPage, removeUser, batchRemoveUser, editUser, addUser } from '../../api/api';

    export default {
        data() {
            return {
                filters: {
                    keyword: ''
                },
                total: 0,
                page: 1,
                pageSize:5,
                listLoading: false,
                sels: [],//列表选中列

                employeeFormVisible: false,//编辑界面是否显示
                employeeLoading: false,
                employeeFormRules: {
                    email: [
                        { required: true, message: '请输入邮箱', trigger: 'blur' }
                    ],
                    phone: [
                        { required: true, message: '请输入电话', trigger: 'blur' }
                    ],
                    username: [
                        { required: true, message: '请输入姓名', trigger: 'blur' }
                    ]
                },
                title:"",
                //编辑界面数据
                employeeForm: {
                    id:null,
                    username: '',
                    email:'',
                    phone:'',
                    state:1,
                    age: 0,
                    employee:{},
                    shop:{}
                },

                // 关联属性处理
                shops: []

            }
        },
        methods: {
            search() {
                //查询完，原来分页条件已经没用了，要跑到第一页去
                this.page = 1;
                this.getDepartments();
            },

            handleCurrentChange(val) {
                this.page = val;
                this.getEmployees();
            },

            //获取员工列表
            getShops() {
                let para = {
                    currentPage: this.page,
                    pageSize:this.pageSize,
                    keyword: this.filters.keyword
                };
                this.listLoading=true;
                this.$http.post("/shop",para)
                    .then(result=>{
                        result=result.data;
                        this.total=result.totals;
                        this.shops=result.rows;
                        this.listLoading=false;
                    })
                    .catch(result=>{
                        alert("系统错误！")
                    })
            },
            //删除
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    /*let para = { id: row.id };
                    removeUser(para).then((res) => {
                        this.listLoading = false;
                        //NProgress.done();
                        this.$message({
                            message: '删除成功',
                            type: 'success'
                        });
                        this.getUsers();
                    });*/
                    //    由于后端的删除接口使根据resultful风格来编码的，所以我们这里要给他弄成相对应的风格
                    let url = "/employee/"+row.id;
                    this.$http.delete(url)
                        .then(result=> {
                                result=result.data;//{sucess:false,message}
                                //去除忙等框
                                this.listLoading = false;

                                if (result.success) {
                                    //删除成功我们跳回第一页，防止有那一页还没数据继续停留的bug
                                    this.page=1;
                                    //提示
                                    this.$message({
                                        message: '删除成功',
                                        type: 'success'
                                    });
                                    //重新查找数据
                                    this.getDepartments();
                                }else {
                                    //提示
                                    this.$message({
                                        message: result.message,
                                        type: 'error'
                                    });
                                    //重新查找数据
                                    this.getEmployees();
                                }
                            }
                        )
                        .catch(result=>{
                            //去除忙等框
                            this.listLoading = false;
                            //提示
                            this.$message({
                                message: '系统错误',
                                type: 'error'
                            });
                        })
                }).catch(() => {

                });
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.title="编辑";
                this.employeeFormVisible = true;
                this.employeeForm = Object.assign({}, row);
            },
            //显示新增界面
            handleAdd: function () {
                this.title="新增";
                this.employeeForm = {//清空
                    /*<id property="id" column="id"></id>
                    <result property="username" column="username"></result>
                    <result property="email" column="email"></result>
                    <result property="phone" column="phone"></result>
                    <result property="state" column="state"></result>
                    <result property="age" column="age"></result>*/
                    id:null,
                    username: '',
                    email:'',
                    phone:'',
                    state: 1,
                    age: 0,
                    department:null,
                    logininfo:null,
                    shop:null
                };
                this.employeeFormVisible = true; //显示新增框
            },
            //保存
            save: function () {
                this.$refs.employeeForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.employeeLoading = true;
                            /*//NProgress.start();
                            let para = Object.assign({}, this.employeeForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            editUser(para).then((res) => {
                                this.employeeLoading = false;
                                //NProgress.done();
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['employeeForm'].resetFields();
                                this.employeeFormVisible = false;
                                this.getUsers();
                            });*/

                            //	我们为了在下面做添加和修改，因为我们之前将数据双向绑定，所以我们对数据操作之前我们先拷贝一份数据
                            let para = Object.assign({}, this.employeeForm);
                            //我们发闪送请求到后台，直接保存数据
                            this.$http.put("/employee",para)
                                .then(result=>{
                                    result=result.data;
                                    if (result.success){
                                        //成功就去除忙等狂
                                        this.employeeLoading = false;
                                        this.$message({
                                            message: '提交成功',
                                            type: 'success'
                                        });
                                        //重新获取数据
                                        this.getEmployees();
                                    }else {
                                        //失败就去除忙等狂
                                        this.employeeLoading = false;
                                        this.$message({
                                            message: result.message,
                                            type: 'error'
                                        });
                                        //重新获取数据
                                        this.getEmployees();
                                    }
                                    this.employeeFormVisible = false;
                                })
                                .catch(result=>{
                                    this.employeeLoading = false;
                                    this.employeeFormVisible = false;
                                    alert("系统错误")
                                })
                        });
                    }
                });
            },
            selsChange: function (sels) {
                this.sels = sels;
            },

            //合并两张表
            arraySpanMethod({ row, column, rowIndex, columnIndex }) {
                if (rowIndex % 2 === 0) {
                    if (columnIndex === 0) {
                        return [1, 2];
                    } else if (columnIndex === 1) {
                        return [0, 0];
                    }
                }
            },

            //合并两张表
            objectSpanMethod({ row, column, rowIndex, columnIndex }) {
                if (columnIndex === 0) {
                    if (rowIndex % 2 === 0) {
                        return {
                            rowspan: 2,
                            colspan: 1
                        };
                    } else {
                        return {
                            rowspan: 0,
                            colspan: 0
                        };
                    }
                }
            },
            //批量删除
            batchRemove: function () {
                //我们不需要toString，因为我们直接返回一个数组给后台进行遍历一个个删除
                var ids = this.sels.map(item => item.id);
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    //NProgress.start();
                    // let para = { ids: ids };
                    /* batchRemoveDepartment(para).then((res) => {
                         this.listLoading = false;
                         //NProgress.done();
                         this.$message({
                             message: '删除成功',
                             type: 'success'
                         });
                         this.getDepartments();
                     });*/
                    //传递数组参数到后台批量删除，不需要let para = { ids: ids };
                    this.$http.patch("/employee",ids)
                        .then(result=>{
                            result = result.data;
                            //去除忙等框
                            this.listLoading = false;
                            if (result){
                                //成功提示
                                this.$message({
                                    message: '删除成功',
                                    type: 'success'
                                });
                                this.page =1; //删除后跳转第一页
                                //从新获取数据
                                this.getDepartments();
                            }else {
                                //去除忙等框
                                this.listLoading = false;
                                //失败提示
                                this.$message({
                                    message: '删除成功'+ result.message,
                                    type: 'error'
                                });
                                //从新获取数据
                                this.getEmployees();
                            }
                        })
                        .catch(result=>{
                            alert("系统错误");
                            this.getEmployees();
                            this.listLoading = false;
                        })

                }).catch(() => {

                });
            }
        },
        mounted() {
            this.getShops();
            this.getDepartments();
        }
    }

</script>

<style scoped>
</style>